package com.bjpowernode.app.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/loginAction")
    public String loginAction(Model model, @RequestParam String username, @RequestParam String password) {
        String mess = "";
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken();
        usernamePasswordToken.setUsername(username);
        usernamePasswordToken.setPassword(password.toCharArray());
        try {
            subject.login(usernamePasswordToken);
            return "redirect:admin/index";
        } catch (LockedAccountException la) {
            mess = la.getMessage();
            System.out.println("LockedAccountException");

        } catch (DisabledAccountException da) {
            mess = da.getMessage();
            System.out.println("DisabledAccountException");

        } catch (UnknownAccountException ua) {
//            mess = ua.getMessage();
            mess = "账户不存在";
            System.out.println("UnknownAccountException");

        } catch (ExcessiveAttemptsException ea) {
            mess = ea.getMessage();
            System.out.println("ExcessiveAttemptsException");

        } catch (IncorrectCredentialsException ia) {
            mess = ia.getMessage();
            mess = "密码错误";
            System.out.println("IncorrectCredentialsException");

        } catch (ExpiredCredentialsException ec) {
            mess = ec.getMessage();
            System.out.println("ExpiredCredentialsException");

        } catch (Exception e) {
            mess = e.getMessage();
            System.out.println("Exception");
        }
        model.addAttribute("mess", mess);
        return "mess";
    }
}
